import { _decorator, CCFloat, Component, RichText, UITransform } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('RichTextCheck')
export class RichTextCheck extends Component {
	@property(CCFloat)
	private height: number = 0;
	@property(CCFloat)
	private width: number = 0;

	private richtext: RichText;
	private ui: UITransform

	private originFontSize: number;
	private originLineHeight: number;

	protected onLoad(){
		this.richtext = this.node.getComponent(RichText);
		this.ui = this.node.getComponent(UITransform);
		this.originFontSize = this.richtext.fontSize;
		this.originLineHeight = this.richtext.lineHeight;
		this.calculating = true;
		this.max_full_size = this.originFontSize;
		this.min_full_size = 0;
	}

	private text: string;
	private calculating: boolean = false;

	private max_full_size: number;
	private min_full_size: number;

	protected lateUpdate(dt: number): void {
		if(!this.text) this.text = this.richtext.string;

		if(this.richtext.string!=this.text){
			this.text = this.richtext.string;
			this.calculating = true;
			this.max_full_size = this.originFontSize;
			this.min_full_size = 0;
		}

		if(this.calculating) this.calculateFontSize();
	}

	private calculateFontSize(){
		if(this.ui.width > this.width || this.ui.height > this.height){
			this.max_full_size = this.richtext.fontSize;
		}else{
			this.min_full_size = this.richtext.fontSize;
		}
		let size = abd.$planet_number_poof$.$planet_fixedNum_poof$((this.max_full_size + this.min_full_size) / 2, 2);
		let line_height = abd.$planet_number_poof$.$planet_fixedNum_poof$(size * this.originLineHeight / this.originFontSize, 2);
		this.richtext.fontSize = size;
		this.richtext.lineHeight = line_height;
		this.calculating = (this.max_full_size-this.min_full_size) > 0.02;
	}
}

